// -*- mode:c++ -*-
//
// 2009-2010 HIT Microelectronic Center all rights reserved
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer;
// redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution;
// neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// Date: Dec. 2009
// Authors: Gou Pengfei

////////////////////////////////////////////////////////////////////
//
// Memory-format instructions of TRIPS
//

output header {{

    /**
     * Base class for general TRIPS memory-format instructions.
     */
    class Memory : public TRIPSStaticInst
    {
      protected:
        /// Memory request flags.  See mem/request.hh
        Request::Flags memAccessFlags;

        /// offset of TRIPS memory access instructions
        int64_t _offset;

        /// Predication bits
	uint32_t pr;
	
        /// Constructor
        Memory(const char *mnem, MachInst _machInst, OpClass __opClass)
            : TRIPSStaticInst(mnem, _machInst, __opClass),
              _offset(sext<9>(IMM)), pr(PR)
        {
        	// Initial the _lsID;
        	_lsID = LSID;
        	switch(pr){
				case 0x0:_predication = Disable;break;
				case 0x2:_predication = PredUponFalse;break;
				case 0x3:_predication = PredUponTrue;break;
				default: _predication = Reserved; 
		}
        }
    };

   class Load : public Memory
    {
      protected:
	
        /// Constructor
        Load(const char *mnem, MachInst _machInst, OpClass __opClass)
            : Memory(mnem, _machInst, __opClass)
        {
        }

        std::string
        generateDisassembly(Addr pc, const SymbolTable *symtab) const;
    };
    
   class Store : public Memory
    {
      protected:
	
        /// Constructor
        Store(const char *mnem, MachInst _machInst, OpClass __opClass)
            : Memory(mnem, _machInst, __opClass)
        {
        }

        std::string
        generateDisassembly(Addr pc, const SymbolTable *symtab) const;
    };
    
}};


output decoder {{

    std::string
    Load::generateDisassembly(Addr pc, const SymbolTable *symtab) const
    {
        return csprintf("%-10s lsid[%d], offset[0x%x], %s", mnemonic, _lsID, _offset, printConsumer(0));
    }
    
    std::string
    Store::generateDisassembly(Addr pc, const SymbolTable *symtab) const
    {
        return csprintf("%-10s lsid[%d], offset[0x%x]", mnemonic, _lsID, _offset);
    }
    
}};

output exec {{
    /** return data in cases where there the size of data is only
        known in the packet
    */
    uint64_t getMemData(%(CPU_exec_context)s *xc, Packet *packet) {
        switch (packet->getSize())
        {
          case 1:
            return packet->get<uint8_t>();

          case 2:
            return packet->get<uint16_t>();

          case 4:
            return packet->get<uint32_t>();

          case 8:
            return packet->get<uint64_t>();

          default:
            std::cerr << "bad store data size = " << packet->getSize() << std::endl;

            assert(0);
            return 0;
        }
    }


}};

def template LoadStoreDeclare {{
    /**
     * Static instruction class for "%(mnemonic)s".
     */
    class %(class_name)s : public %(base_class)s
    {
      public:

        /// Constructor.
        %(class_name)s(ExtMachInst machInst);

        %(BasicExecDeclare)s

        %(EACompDeclare)s

        %(InitiateAccDeclare)s

        %(CompleteAccDeclare)s
    };
}};

def template EACompDeclare {{
    Fault eaComp(%(CPU_exec_context)s *, Trace::EdgeInstRecord *) const;
}};

def template InitiateAccDeclare {{
    Fault initiateAcc(%(CPU_exec_context)s *, Trace::EdgeInstRecord *) const;
}};


def template CompleteAccDeclare {{
    Fault completeAcc(Packet *, %(CPU_exec_context)s *, Trace::EdgeInstRecord *) const;
}};

def template LoadStoreConstructor {{
    inline %(class_name)s::%(class_name)s(ExtMachInst machInst)
         : %(base_class)s("%(mnemonic)s", machInst, %(op_class)s)
    {
        %(constructor)s;
    }
}};


def template StoreEAComp {{
    Fault
    %(class_name)s::eaComp(%(CPU_exec_context)s *xc,
                                   Trace::EdgeInstRecord *traceData) const
    {
        Addr EA;
        Fault fault = NoFault;
        
        %(op_decl)s;
        %(op_rd)s;
        %(ea_code)s;

        if (fault == NoFault) {
            %(memacc_code)s;
        }

        // NOTE: Trace Data is written using execute or completeAcc templates
        if (fault == NoFault) {
            // Set effective address.
            //xc->setEA(EA);

            // Set access size
            //int acc_size = sizeof(uint%(mem_acc_size)d_t);
            //xc->memAccSize = acc_size;

            // Set data to store
            //uint%(mem_acc_size)d_t gData = htog(Mem);
            //assert(!xc->memData);
            //xc->memData = new uint8_t[64];
            //memcpy(xc->memData,&gData,acc_size);

            fault = xc->effAddrComp((uint%(mem_acc_size)d_t&)Mem, EA,
                  memAccessFlags, NULL);
            
        }

        return fault;
    }
}};

def template LoadEAComp {{
    Fault
    %(class_name)s::eaComp(%(CPU_exec_context)s *xc,
                                   Trace::EdgeInstRecord *traceData) const
    {
        Addr EA;
        Fault fault = NoFault;
        
        %(op_decl)s;
        %(op_rd)s;
        %(ea_code)s;

        if (fault == NoFault) {
            %(memacc_code)s;
        }

        // NOTE: Trace Data is written using execute or completeAcc templates
        if (fault == NoFault) {
            // Set effective address.
            xc->setEA(EA);

            // Set access size
            int acc_size = sizeof(uint%(mem_acc_size)d_t);
            xc->memAccSize = acc_size;
        }

        return fault;
    }
}};

def template LoadExecute {{
    Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
                                  Trace::EdgeInstRecord *traceData) const
    {
        Addr EA;
        Fault fault = NoFault;

        %(op_decl)s;
        %(op_rd)s;
        %(ea_code)s;

        if (fault == NoFault) {
            fault = xc->read(EA, (uint%(mem_acc_size)d_t&)Mem, memAccessFlags);
            %(memacc_code)s;
        }

        if (fault == NoFault) {
            %(op_wb)s;
        }

        return fault;
    }
}};


def template LoadInitiateAcc {{
    Fault %(class_name)s::initiateAcc(%(CPU_exec_context)s *xc,
                                      Trace::EdgeInstRecord *traceData) const
    {
        Addr EA;
        Fault fault = NoFault;

        %(op_src_decl)s;
        %(op_rd)s;
        %(ea_code)s;

        if (fault == NoFault) {
            fault = xc->read(EA, (uint%(mem_acc_size)d_t &)Mem, memAccessFlags);
        }

        return fault;
    }
}};

def template LoadCompleteAcc {{
    Fault %(class_name)s::completeAcc(Packet *pkt,
                                      %(CPU_exec_context)s *xc,
                                      Trace::EdgeInstRecord *traceData) const
    {
        Fault fault = NoFault;

        %(op_decl)s;
        %(op_rd)s;

        Mem = pkt->get<typeof(Mem)>();

        if (fault == NoFault) {
            %(memacc_code)s;
        }

        if (fault == NoFault) {
            %(op_wb)s;
        }

        return fault;
    }
}};

def template StoreExecute {{
    Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
                                  Trace::EdgeInstRecord *traceData) const
    {
        Fault fault = NoFault;
        Addr EA = 0;

        assert(xc->effAddrValid);

        %(op_dest_decl)s;
        
        if (fault == NoFault) {
            EA = xc->getEA();
            Mem = *((uint%(mem_acc_size)d_t *)xc->memData);
        }

        if (fault == NoFault) {
            %(op_wb)s;
            
            fault = xc->write((uint%(mem_acc_size)d_t&)Mem, EA,
                              memAccessFlags, NULL);
            //if (traceData) { traceData->setData(Mem); }

            //if (traceData) { traceData->setData(getMemData(xc, pkt)); }
        }

        return fault;
    }
}};

def template StoreInitiateAcc {{
    Fault %(class_name)s::initiateAcc(%(CPU_exec_context)s *xc,
                                      Trace::EdgeInstRecord *traceData) const
    {
        Addr EA;
        Fault fault = NoFault;

        %(op_decl)s;
        %(op_rd)s;
        %(ea_code)s;

        if (fault == NoFault) {
            %(memacc_code)s;
        }

        if (fault == NoFault) {
            fault = xc->write((uint%(mem_acc_size)d_t&)Mem, EA,
                              memAccessFlags, NULL);
            //if (traceData) { traceData->setData(Mem); }
        }

        return fault;
    }
}};

def template StoreCompleteAcc {{
    Fault %(class_name)s::completeAcc(Packet *pkt,
                                      %(CPU_exec_context)s *xc,
                                      Trace::EdgeInstRecord *traceData) const
    {
        Fault fault = NoFault;

        panic("Unimplemented func: completeAcc.\n");

        return fault;
    }
}};

let {{
def MemoryBase(name, Name, ea_code, memacc_code, mem_flags, inst_flags,
                  postacc_code = '', base_class = 'Memory',
                  decode_template = BasicDecode, exec_template_base = ''):
    # Make sure flags are in lists (convert to lists if not).

    mem_flags = makeList(mem_flags)
    inst_flags = makeList(inst_flags)

    # add hook to get effective addresses into execution trace output.
    ea_code += '\nif (traceData) { traceData->setAddr(EA); }\n'

    # Some CPU models execute the memory operation as an atomic unit,
    # while others want to separate them into an effective address
    # computation and a memory access operation.  As a result, we need
    # to generate three StaticInst objects.  Note that the latter two
    # are nested inside the larger "atomic" one.

    # Generate InstObjParams for each of the three objects.  Note that
    # they differ only in the set of code objects contained (which in
    # turn affects the object's overall operand list).
    iop = InstObjParams(name, Name, base_class,
                        { 'ea_code':ea_code, 'memacc_code':memacc_code, 'postacc_code':postacc_code },
                        inst_flags)

    if mem_flags:
        mem_flags = [ 'Request::%s' % flag for flag in mem_flags ]
        s = '\n\tmemAccessFlags = ' + string.join(mem_flags, '|') + ';'
        iop.constructor += s

    # select templates

    # The InitiateAcc template is the same for StoreCond templates as the
    # corresponding Store template..
    StoreCondInitiateAcc = StoreInitiateAcc

    fullExecTemplate = eval(exec_template_base + 'Execute')
    initiateAccTemplate = eval(exec_template_base + 'InitiateAcc')
    completeAccTemplate = eval(exec_template_base + 'CompleteAcc')
    eaCompTemplate = eval(exec_template_base + 'EAComp')

    # (header_output, decoder_output, decode_block, exec_output)
    return (LoadStoreDeclare.subst(iop),
            LoadStoreConstructor.subst(iop),
            decode_template.subst(iop),
            fullExecTemplate.subst(iop)
            + eaCompTemplate.subst(iop)
            + initiateAccTemplate.subst(iop)
            + completeAccTemplate.subst(iop))
}};

output header {{
        std::string inst2string(MachInst machInst);
}};

output decoder {{

std::string inst2string(MachInst machInst)
{
    string str = "";
    uint32_t mask = 0x80000000;

    for(int i=0; i < 32; i++) {
        if ((machInst & mask) == 0) {
            str += "0";
        } else {
            str += "1";
        }

        mask = mask >> 1;
    }

    return str;
}

}};

def format LoadMemory(memacc_code, ea_code = {{ EA = Op0.ud + _offset; }},
                     mem_flags = [], inst_flags = []) {{

    inst_flags+=['IQOPerands','IsEDGE',{'numConsumer':1}]
    (header_output, decoder_output, decode_block, exec_output) = \
        MemoryBase(name, Name, ea_code, memacc_code, mem_flags, inst_flags, base_class='Load',
                      exec_template_base = 'Load')
}};

def format StoreMemory(memacc_code, ea_code = {{EA = Op0.ud + _offset; }},
                     mem_flags = [], inst_flags = []) {{
                     
    inst_flags+=['IQOPerands','IsEDGE',{'numConsumer':0}]
    (header_output, decoder_output, decode_block, exec_output) = \
        MemoryBase(name, Name, ea_code, memacc_code, mem_flags, inst_flags, base_class='Store',
                      exec_template_base = 'Store')
}};



